import datetime
import json
from utils.views import LoginRequiredJSONMixin
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View

from apps.house.models import House
from apps.order.models import Order


class TestView(View):
    """测试类"""

    def post(self, request):

        json_dict = json.loads(request.body.decode())
        return JsonResponse(json_dict)


class OrderView(LoginRequiredJSONMixin, View):
    """添加订单，获取订单"""

    def post(self, request):
        """添加订单"""

        # 接收参数
        json_dict = json.loads(request.body.decode())
        house_id = json_dict.get('house_id')
        start_date = json_dict.get('start_date')
        end_date = json_dict.get('end_date')
        # 验证参数
        if not all([house_id, start_date, end_date]):
            return JsonResponse({'errno': 4103,
                                 'errmsg': '参数错误',
                                 'data': {}})
        try:
            house = House.objects.get(id=house_id)
        except Exception as e:
            return JsonResponse({'errno': 4103,
                                 'errmsg': '参数错误',
                                 'data': {}})

        # 业务逻辑
        # 根据start_date和house_id获取当前房屋的订单，
        # 查看房屋是否已租出，如果房屋已出租，返回响应下单失败，
        # 如果房屋未租出，查看用户是否满足最小入住时间，满足则生成订单
        # 生产订单，则数据入库
        try:
            order = Order.objects.get(house=house, begin_date=start_date)
            # 房屋已租出
            return JsonResponse({'errno': 4003,
                                 'errmsg': '房屋已预定',
                                 'data': {}})
            pass
        except Exception as e:
            # 房屋未租出
            # 判断用户入住天数是否满足
            start_date_list = start_date.split('-', 2)
            end_date_list = end_date.split('-', 2)
            # 计算入住天数
            d1 = datetime.datetime(int(start_date_list[0]), int(start_date_list[1]), int(start_date_list[2]))
            d2 = datetime.datetime(int(end_date_list[0]), int(end_date_list[1]), int(end_date_list[2]))

            date_days = (d2 - d1).days
            if date_days < house.min_days:
                return JsonResponse({'errno': 4004,
                                     'errmsg': '入住天数小于最小入住天数',
                                     'data': {}})
            house_max_days = house.max_days
            if house.max_days == 0:
                house_max_days = 999999
            if date_days > house_max_days:
                return JsonResponse({'errno': 4004,
                                     'errmsg': '入住天数大于最大入住天数',
                                     'data': {}})
        amount = date_days * house.price
        # 数据入库
        try:
            order = Order.objects.create(
                user=request.user,
                house=house,
                begin_date=start_date,
                end_date=end_date,
                days=date_days,
                house_price=house.price,
                amount=amount,
                status=Order.ORDER_STATUS['WAIT_ACCEPT'],
                comment=''
            )
        except Exception as e:
            return JsonResponse({'errno': 4004,
                                 'errmsg': '生成订单错误',
                                 'data': {}})
        # 返回响应
        return JsonResponse({'data': {'order_id': order.id},
                             'errno': 0,
                             'errmsg': '下单成功'})

    def get(self, request):
        """获取订单"""
        # 获取参数
        role = request.GET.get('role')
        if role == 'custom':
            # 展示房客订单信息
            orders_list = []
            try:
                user = request.user
                orders = Order.objects.filter(user=user).order_by('create_time')
                orders = orders[::-1]
                for order in orders:
                    order_dict = {}
                    amount = order.amount
                    comment = order.comment
                    ctime = order.create_time
                    days = order.days
                    end_date = order.end_date
                    # house = House.objects.get(house=order.house)
                    house = order.house
                    img_url = house.index_image_url
                    order_id = order.id
                    start_date = order.begin_date
                    status = order.status
                    status = order.ORDER_STATUS_ENUM[status]
                    title = house.title
                    order_dict['amount'] = amount
                    order_dict['comment'] = comment
                    order_dict['ctime'] = ctime
                    order_dict['days'] = days
                    order_dict['end_date'] = end_date
                    order_dict['img_url'] = img_url
                    order_dict['order_id'] = order_id
                    order_dict['start_date'] = start_date
                    order_dict['status'] = status
                    order_dict['title'] = title
                    orders_list.append(order_dict)
                return JsonResponse({'errno': 0,
                                     'errmsg': 'OK',
                                     'data': {'orders': orders_list}})
            except Exception as e:
                return JsonResponse({'errno': 4002,
                                     'errmsg': '无订单信息',
                                     'data': {}})

        elif role == 'landlord':
            # 展示房东订单信息
            # 查询用户的房屋信息，根据房屋信息查询订单信息
            try:
                houses = House.objects.filter(user=request.user)
                orders_list = []
                for house in houses:
                    try:
                        # orders = Order.objects.filter(house=house)
                        orders = Order.objects.filter(house=house).order_by('create_time')
                        orders = orders[::-1]
                        for order in orders:
                            order_dict = {}
                            amount = order.amount
                            comment = order.comment
                            ctime = order.create_time
                            days = order.days
                            end_date = order.end_date
                            img_url = house.index_image_url
                            order_id = order.id
                            start_date = order.begin_date
                            status = order.status
                            status = order.ORDER_STATUS_ENUM[status]
                            title = house.title
                            order_dict['amount'] = amount
                            order_dict['comment'] = comment
                            order_dict['ctime'] = ctime
                            order_dict['days'] = days
                            order_dict['end_date'] = end_date
                            order_dict['img_url'] = img_url
                            order_dict['order_id'] = order_id
                            order_dict['start_date'] = start_date
                            order_dict['status'] = status
                            order_dict['title'] = title
                            orders_list.append(order_dict)
                    except Exception as e:
                        return JsonResponse({'errno': 4002,
                                             'errmsg': '无订单信息',
                                             'data': {}})
                return JsonResponse({'errno': 0,
                                     'errmsg': 'OK',
                                     'data': {'orders': orders_list}})
            except Exception as e:
                return JsonResponse({'errno': 4002,
                                     'errmsg': '无房屋信息',
                                     'data': {}})

        else:
            return JsonResponse({'errno': 4103,
                                 'errmsg': '参数错误',
                                 'data': {}})


class UpdateOrderView(LoginRequiredJSONMixin, View):
    """接单，拒单"""

    def put(self, request, order_id):
        """修改订单"""
        json_dict = json.loads(request.body.decode())
        action = json_dict.get('action')
        if action == 'reject':
            reason = json_dict.get('reason')
            if not all([action, reason]):
                return JsonResponse({'errno': 4103,
                                     'errmsg': '参数错误'})
            try:
                order = Order.objects.get(id=order_id)
                order.status = Order.ORDER_STATUS['REJECTED']
                order.comment = reason
                order.save()
                return JsonResponse({'errno': 0,
                                     'errmsg': '操作成功'})
            except Exception as e:
                return JsonResponse({'errno': 4001,
                                     'errmsg': '订单查询错误'})
        if action is None:
            return JsonResponse({'errno': 4103,
                                 'errmsg': '参数错误'})

        # 修改订单信息
        try:
            order = Order.objects.get(id=order_id)
            order.status = Order.ORDER_STATUS['WAIT_COMMENT']
            order.save()
            return JsonResponse({'errno': 0,
                                 'errmsg': '操作成功'})
        except Exception as e:
            return JsonResponse({'errno': 4001,
                                 'errmsg': '订单查询错误'})


class UpdateOrderCommitView(LoginRequiredJSONMixin, View):
    """修改订单评论"""

    def put(self, request, order_id):
        """修改订单评论"""
        try:
            order = Order.objects.get(id=order_id)
            if order.status == order.ORDER_STATUS['WAIT_COMMENT']:
                comment = json.loads(request.body.decode()).get('comment')
                order.comment = comment
                order.status = order.ORDER_STATUS['COMPLETE']
                order.save()
                return JsonResponse({'errno': 0,
                                     'errmsg': '评论成功'})
            else:
                return JsonResponse({'errno': 4004,
                                     'errmsg': '订单已评论！'})
        except Exception as e:
            return JsonResponse({'errno': 4103,
                                 'errmsg': '订单查询错误'})


